from django.shortcuts import get_object_or_404, render_to_response
from django.core.paginator import ObjectPaginator, InvalidPage
from django.template import RequestContext
from django.http import HttpResponse, Http404
from django.conf import settings

from models import *
from lugtrelew.tags.models import TaggedItem

def listar_blogs(request):
    lista_blogs = Blog.objects.all()
    return generar_listado_paginado(request, lista_blogs, "blog/listar_blogs.html")

def listar_posts_de_blog(request, slug_blog):
    
    #Un blog del usuario
    blog = get_object_or_404(Blog,slug = slug_blog)
    posts = blog.blog_posts.all()
    #return generar_listado_paginado(request, posts, "blog/listar_posts.html", username=blog.autor.username, slug=slug_blog, titulo=blog.titulo, descripcion=blog.descripcion )
    return generar_listado_paginado(request, posts, "blog/listar_posts.html", blog=blog )


def leer_post(reuest, slug_blog, dia, mes, anio, slug_post):
    
    dia = int(dia); mes=int(mes); anio=int(anio)
    blog = get_object_or_404(Blog, slug = slug_blog)
    post = get_object_or_404(Post, blog = blog, fecha__month = mes,fecha__year = anio,slug = slug_post)
    
    post.post_leido()
    
    return render_to_response('blog/leer_post.html', {'post': post, 'otros': {'blog': blog}})
        

def listar_todos_los_posts(request):
    posts = Post.objects.all()
    return generar_listado_paginado(request, posts, "blog/listar_posts.html" )


"""
CORTE Y CONFECCION ;)
"""
def generar_listado_paginado(request, lista, template, **otros):
    ''' crea un listado con paginacion '''
    
    # en settings se encuentra el valor de la variable ITEMS_X_PAGINA
    paginator = ObjectPaginator(lista, settings.ITEMS_X_PAGINA )
   
    try:
        page = int(request.GET.get('page', '1'))
        lista = paginator.get_page(page - 1 )
   
    except ValueError:
       raise Http404
        
    except InvalidPage: 
        raise Http404
        
            
    return render_to_response(template, {
     'lista': lista,
     'is_paginated': paginator.pages > 1,
     'has_next': paginator.has_next_page(page - 1),
     'has_previous': paginator.has_previous_page(page -1 ),
     'current_page': page,
     'next_page': page + 1,
     'previous_page': page - 1,
     'pages': paginator.pages,
     'hits': paginator.hits,
     'otros': otros,
     },
     context_instance = RequestContext(request))
    




#
# Listar todos los post que corresponden a un tag en especial
#
def listar_posts_por_tag(request, tag):
    " Obtiene todos los TaggItems que correspondan a un tag y que sean para Post, ver content_type=\"post\" "
    tagged_items = TaggedItem.objects.filter(slug=tag, content_type__name='post').order_by('-id')
    return generar_listado_paginado(request, tagged_items, "blog/listar_post_por_tag.html", tag=tag )
    
    
    

    
    

